﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using In.Api.Dto.Notify;
using In.Api.Dto.Notify.Notification;
using Newtonsoft.Json;
using Quartz;
using Rmq.Center;

namespace In.TaskRunner.QuartzJobs
{
    public class HaltInfoJob:IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(HaltInfoJob));

        public void Execute(IJobExecutionContext context)
        {
            var connstr = ConfigurationManager.ConnectionStrings["HISNoticeEntity"].ConnectionString;
            var connection = new OdbcConnection(connstr);
            connection.Open();
            string sql = "select RowId,HaltDate, DeptId, DeptName,DoctorId, DoctName, RegType,TimeSlice,StartTime,EndTime,OPTime from HaltInfo where RowNum<10";
            var adapter = new OdbcDataAdapter(sql, connection);
            try
            {
                var dt = new DataTable();
                adapter.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    Console.WriteLine("找到{0}条停诊通知", dt.Rows.Count);
                }

                foreach (DataRow dr in dt.Rows)
                {
                    var rowId = dr["RowId"].ToString();
                    var haltInfo = new HaltInfo();
                    if (dr["HaltDate"].IsDBNull())
                    {
                        haltInfo.HaltDate = null;
                    }
                    else
                    {
                        haltInfo.HaltDate = dr["HaltDate"].ToDateTime().ToString("yyyy-MM-dd");
                    }
                    haltInfo.DeptId = dr["DeptId"].ToString();
                    haltInfo.DeptName = dr["DeptName"].ToString();
                    haltInfo.DoctorId = dr["DoctorId"].ToString();
                    haltInfo.DoctorName = dr["DoctName"].ToString();
                    haltInfo.RegType = dr["RegType"].ToString();
                    haltInfo.TimeSlice = dr["TimeSlice"].ToString();
                    haltInfo.StartTime = dr["StartTime"].ToString();
                    haltInfo.EndTime = dr["EndTime"].ToString();
                    if (dr["OPTime"].IsDBNull())
                    {
                        haltInfo.OPTime = null;
                    }
                    else
                    {
                        haltInfo.OPTime = dr["OPTime"].ToDateTime().ToString("yyyy-MM-dd");
                    }

                    ProcessNotice(haltInfo);

                    DeleteNotice(rowId);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(JsonConvert.SerializeObject(ex));
                Logger.ErrorFormat("HaltInfoJob出错：{0}", ex.Message);
            }
            adapter.Dispose();
            connection.Close();
            connection.Dispose();
        }

        private static readonly HttpClient HttpClient = new HttpClient();

        private void ProcessNotice(HaltInfo haltInfo)
        {
            var notification = new NotificationRequest()
            {
                NotificationType = "HaltNotice",
                NotificationInfo = JsonConvert.SerializeObject(haltInfo)
            };
            Console.WriteLine("停诊通知:{0}", notification.NotificationInfo);

            try
            {
                //var wxApiAddress = ConfigurationManager.AppSettings["WxNotificationApiBaseAddress"];
                //var alipayApiAddress = ConfigurationManager.AppSettings["AlipayNotificationApiBaseAddress"];
                
                var hospMessageProducer = new HospMessageProducer();
                hospMessageProducer.Publish(new HospMessageMsg()
                {
                    NotificationType = notification.NotificationType,
                    NotificationInfo = notification.NotificationInfo
                });

                //HttpClient.PostAsJsonAsync(alipayApiAddress, notification);
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("发送停诊通知出错：{0}", e.Message);
            }
        }

        private void DeleteNotice(string rowId)
        {
            var connstr = ConfigurationManager.ConnectionStrings["HISNoticeEntity"].ConnectionString;
            OdbcConnection connection = new OdbcConnection(connstr);
            connection.Open();
            string sql = string.Format("delete from HaltInfo where RowId=?");
            var cmd = new OdbcCommand(sql, connection);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add(new OdbcParameter("@RowId", rowId));
            cmd.ExecuteNonQuery();
            connection.Close();
            connection.Dispose();
            //Notify(ServiceStatus.BUSY, "已经删除了一条停诊通知");
        }
    }
}
